package swing;

import cz.muni.fi.pv168.ContactManager.*;

import javax.swing.*;
import java.awt.event.*;

public class AddContact extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField typeText;
    private JTextField valueText;
    
    Contact contact;
    Person person;
    ContactManagerImpl contactManager = new ContactManagerImpl();
    AddressBookManagerImpl addressBookManager = new AddressBookManagerImpl();

    private void addContact(Person person, Contact contact) {      //pomocna metoda pro konstruktory
        addressBookManager.setDataSource(DBUtil.getDataSource());
        contactManager.setDataSource(DBUtil.getDataSource());

        if (contact!=null){
            this.contact = contact;
            typeText.setText(contact.getType());
            valueText.setText(contact.getValue());
        }
        this.person = person;
        this.contact = contact;

        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

// call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    public AddContact(Contact contact) {
        addContact(null, contact);
    }

    public AddContact(Person person) {
        addContact(person, null);
    }

    private void onOK() {
        if(typeText.getText()!=null || typeText.getText()!="" || valueText.getText()!=null || typeText.getText()!=""){
            if (contact == null) contact = new Contact();
            contact.setType(typeText.getText());
            contact.setValue(valueText.getText());
            if (contact.getId() == null) {
                contact = contactManager.createContact(contact);
                addressBookManager.addContactToPerson(person, contact);
            } else contactManager.updateContact(contact);
        }
        dispose();
    }

    private void onCancel() {
// add your code here if necessary
        dispose();
    }

}
